<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="mergeOpen = true" v-permission="'manage.add'"
      style="margin-left: 10px">合并</el-button>
    <el-button type="primary" class="fr" @click="createItem" v-permission="'manage.add'">创建</el-button>
    <div class="filter-container">
      <el-input style="width: 150px" placeholder="请输入订单" clearable prefix-icon="el-icon-search" class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.queryString.order_id"></el-input>
      <el-input style="width: 150px" placeholder="请输入型号" clearable prefix-icon="el-icon-search" class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.queryString.finish_model"></el-input>
      <el-select class="filter-item" style="width: 200px" clearable @clear="getList" @change="getList"
        v-model="query.queryString.stauts">
        <el-option label="ALL" value=""></el-option>
        <el-option label="初始" value="初始"></el-option>
        <el-option label="已下工单" value="已下工单"></el-option>
        <el-option label="已结单" value="已结单"></el-option>
      </el-select>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:operation="v">
        <a href="#" class="text-blue" @click.prevent="editItem(v.row, v.$index)" v-permission="'manage.edit'">编辑</a>
        <span>&nbsp;</span>
        <span>&nbsp;</span>
        <a href="#" class="text-blue" @click.prevent="splitItem(v.row, v.$index)" v-permission="'manage.edit'">拆分</a>
        <span>&nbsp;</span>
        <span>&nbsp;</span>
        <a href="#" class="text-blue" v-permission="'manage.edit'" @click.prevent="
            () => {
              ;(statementOpen = true), (statementData = v.row)
            }
          ">结单</a>
        <span>&nbsp;</span>
        <span>&nbsp;</span>
        <a href="#" class="text-blue" v-permission="'manage.edit'"
          @click.prevent="workOrderForm(v.row, v.$index)">下工单</a>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList" v-show="total > 0"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>

    <!-- 订单拆分 -->
    <el-dialog title="订单拆分" :visible.sync="splitOpen">
      <el-form :model="splitData" label-position="center">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号码" label-width="80px">
              <el-input v-model="splitData.order_id" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品型号" label-width="80px">
              <el-input v-model="splitData.finish_model" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原始数量" label-width="80px">
              <el-input v-model="splitData.order_nums" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售日期" label-width="80px">
              <el-input v-model="splitData.sale_datetime" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" label-width="80px">
              <el-input v-model="splitData.customer" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" label-width="80px">
              <el-input type="textarea" placeholder="请输入内容" v-model="splitData.remake" :maxlength="200" show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-for="(item, index) in splitNum" :key="index">
          <el-col :span="24">
            <el-form-item label="拆出数量" label-width="80px" class="butBlock">
              <el-row>
                <el-col :span="6">
                  <el-input-number v-model="item.SplitCount" :min="1" :precision="0"></el-input-number>
                </el-col>
                <el-col :span="3.5">
                  <el-button style="margin: 0 10px 0 10px" @click="rowRemove(index)">删除行</el-button>
                </el-col>
                <el-col :span="7">
                  <el-input v-model="item.SplitNumb" placeholder="请输入内容" clearable></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="splitAdd">新增拆分单</el-button>
        <el-button type="primary" @click="splitSubmit" :loading="splitLoading">确 定</el-button>
        <el-button @click="splitOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 订单合并 -->
    <el-dialog title="订单合并" :visible.sync="mergeOpen" width="70%">
      <el-row>
        <el-col :span="2" style="line-height: 32px"> <span>订单编号：</span></el-col>
        <el-col :span="7">
          <el-input v-model="mergeInp" @keyup.enter.native="orderAdd" autocomplete="off" placeholder="请输入完整的订单编号"
            clearable :disabled="orderLoading">
          </el-input>
        </el-col>
        <el-col :span="3" style="margin-left: 15px">
          <el-button type="primary" @click="orderAdd" :loading="orderLoading">查询</el-button>
        </el-col>
      </el-row>
      <el-table ref='dataTable' :data="mergeData" style='margin-top:10px' @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="order_id" label="订单号码" show-overflow-tooltip></el-table-column>
        <el-table-column property="finish_model" show-overflow-tooltip label="成品型号"></el-table-column>
        <el-table-column property="order_nums" label="数量" show-overflow-tooltip></el-table-column>
        <el-table-column property="sale_datetime" label="销售日期" show-overflow-tooltip></el-table-column>
        <el-table-column property="customer" label="客户" show-overflow-tooltip></el-table-column>
        <el-table-column property="stauts" label="状态" show-overflow-tooltip></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="mergeOk" :disabled="mergeChecked.length <2" :loading="mergeLoading">合 并
        </el-button>
        <el-button @click="mergeOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 结单 -->
    <el-dialog title="结单" :visible.sync="statementOpen" width="50%">
      <div style="margin-bottom: 20px">请输入结单操作原因</div>
      <el-input type="textarea" placeholder="请输入内容" v-model="statement_reason" :maxlength="200" show-word-limit>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statementOpen = false">取 消</el-button>
        <el-button type="primary" @click="statement" :loading="statementLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 下工单 -->
    <el-dialog title="下工单" :visible.sync="workOrderOpen">
      <el-form :model="workOrderData" label-position="center">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号码" label-width="80px">
              <el-input v-model="workOrderData.order_id" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品型号" label-width="80px">
              <el-input v-model="workOrderData.finish_model" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原始数量" label-width="80px">
              <el-input v-model="workOrderData.order_nums" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售日期" label-width="80px">
              <el-input v-model="workOrderData.sale_datetime" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" label-width="80px">
              <el-input v-model="workOrderData.customer" autocomplete="off" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="height: 50px">
          <el-col :span="12">

            <el-form-item label="工单编号" label-width="80px">
              <el-input v-model='workNum' placeholder="请输入工单编号"></el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" label-width="80px" required>
              <el-select v-model="workType" placeholder="请选择" style="width: 100%" filterable clearable>
                <el-option v-for="item in workTypeData" :key="item.id" :label="item.label" :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" label-width="80px" required>
              <el-date-picker v-model="workTime1" type="date" placeholder="选择日期" style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions1" clearable>
              </el-date-picker>
            </el-form-item>

          </el-col>
          <el-col :span="12" v-show='this.workTime1'>
            <el-form-item label="结束日期" label-width="80px" required>
              <el-date-picker v-model="workTime2" type="date" placeholder="选择日期" style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions2" clearable>
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="workOrderSubmit" :loading="workOrderLoading">确 定</el-button>
        <el-button @click="workOrderOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
export default {
  mixins: [commonMixin],
  name: 'manage',
  data: function () {
    return {
      name: '订单管理',
      mergeInp: '',
      mergeData: [],
      mergeOpen: false,
      splitOpen: false,
      splitLoading: false,
      orderLoading: false,
      mergeLoading: false,
      statementOpen: false,
      statementLoading: false,
      workOrderOpen: false,
      statement_reason: '',
      statementData: {},
      splitData: {},
      workOrderData: {},
      workType: '',
      workTypeData: [],
      workNum: '',
      workNumData: [],
      workTime1: '',
      workTime2: '',
      workOrderLoading: false,
      splitNum: [{ SplitNumb: '', SplitCount: '' }],
      apiList: this.$api.manage,
      apiSingle: this.$api.manageId,
      apiCreate: this.$api.manageCreate,
      postForList: true,
      mergeChecked: [],
      query: {
        page: 1,
        size: 10,
        queryString: {
          stauts: '',
        },
      },
      tableProps: {
        border: true,
        opsColWith: 150, //不定义默认80
        hideOperations: false,
      },
      columns: [
        { title: '订单号码', key: 'order_id' },
        { title: '成品型号', key: 'finish_model' },
        { title: '数量', key: 'order_nums' },
        { title: '销售日期', key: 'sale_datetime' },
        { title: '客户', key: 'customer' },
        { title: '状态', key: 'stauts' },
        { title: '备注', key: 'remake' },
        { title: '最后修改人', key: 'modify_user' },
        { title: '最后修改时间', key: 'modify_time' },
      ],
      fields: [
        { title: '订单号码', key: 'order_id', required: true, span: 12, props: {} },
        {
          title: '成品型号',
          key: 'finish_model',
          required: true,
          options: [],
          name: 'select',
          span: 12,
          props: { filterable: true },
        },
        {
          title: '订单数量',
          key: 'order_nums',
          required: true,
          span: 12,
          name: 'number',
          props: { min: 1, precision: 0, step: 1, controls: false },
        },
        {
          title: '销售日期',
          key: 'sale_datetime',
          span: 12,
          name: 'dateNow',
          props: { 'value-format': 'yyyy-MM-dd HH:mm:ss' },
        },
        { title: '客户', key: 'customer', options: [], name: 'select', span: 12, props: { filterable: true } },
        { title: '备注', key: 'remake', name: 'textarea', props: { maxlength: 200 } },
      ],
      model: [],
      customer: [],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    }
  },
  created() {
    this.getList()
    this.$request(this.$api.dictionary + 'getdirectchildren', { parentType: 'mo_type' }).then((r) => {
      console.log(r)
      this.workTypeData = r
    })
    this.$request(this.$api.orderNum, { page: 1, size: 999 }).then((r) => {
      console.log(r)
      this.workNumData = r.list
    })
    this.$request(this.$api.mat + 'getlist_v10', {
      category: 2,
      page: 1,
      size: 999,
    }).then((r) => {
      this.model = r.list
      let newList = this.model.map((v) => {
        return { ...v, model_ok: v.key_part_no + ' ' + v.key_part_name }
      })
      this.setFieldOptions('finish_model', newList, 'model_ok', ['key_part_no', 'key_part_name'])
    })
    this.$request(this.$api.custom + 'getlist', {
      page: 1,
      size: 999,
    }).then((r) => {
      this.customer = r.list
      let newList = this.customer.map((v) => {
        return { ...v, customer_region: v.cust_code + ' ' + v.cust_name }
      })
      this.setFieldOptions('customer', newList, 'customer_region', ['cust_code', 'cust_name'])
    })
  },
  watch: {
    'data.id': {
      handler(val, o) {
        this.getFieldConfig('order_id').props.disabled = !!val
        this.getFieldConfig('finish_model').props.disabled = !!val
      },
      deep: true,
    },
    mergeOpen(val) {
      if (!val) {
        this.mergeInp = ''
        this.mergeData = []
      }
    },
    statementOpen(val) {
      if (!val) {
        this.statement_reason = ''
      }
    },
    splitOpen(val) {
      if (!val) {
        this.splitNum = [{ SplitNumb: '', SplitCount: '' }]
      }
    },
    workOrderOpen(val) {
      if (!val) {
        this.workNum = ''
        this.workType = ''
        this.workTime1 = ''
        this.workTime2 = ''
      }
    },
  },
  methods: {
    editItem(v) {
      this.pageLoading = true
      let url = this.apiSingle || this.api + 'getbyid'
      this.$request(url, {
        vid: v.id,
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          this.editFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    submit() {
      let url = this.apiCreate
      let data = { ...this.formatBeforeSave(this.data), key_part_no: this.data.finish_model.split(' ')[0] }
      console.log(data, 'ssss')

      let check = this.validataData(this.fields, data)
      console.log(check)
      if (!check) return
      this.submitLoading = true
      this.$request(url, { orders: [data] }, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    splitItem(v) {
      this.pageLoading = true
      let url = this.apiSingle || this.api + 'getbyid'
      this.$request(url, {
        vid: v.id,
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          this.splitNum[0]['SplitNumb'] = `${this.data.order_id}-1`
          this.splitData = this.data
          this.splitOpen = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    splitAdd() {
      this.splitNum = [
        ...this.splitNum,
        { SplitCount: '', SplitNumb: `${this.splitData.order_id}-${this.splitNum.length + 1}` },
      ]
    },
    rowRemove(key) {
      if (this.splitNum.length > 1) {
        this.splitNum = this.splitNum.filter((item, index) => index !== key)
        this.splitNum = this.splitNum.map((item, index) => {
          item.SplitNumb = `${this.splitData.order_id}-${index + 1}`
          return item
        })
      } else {
        this.$message.warning('最少要拆分一条')
      }
    },
    splitSubmit() {
      let res = this.splitNum.every((item) => item.SplitCount && item.SplitNumb)
      if (!res) {
        this.$message.error('内容不能为空')
      } else {
        let url = this.apiCreate
        let data = this.formatBeforeSave(this.data)
        let check = this.validataData(this.fields, data)
        if (!check) return
        this.splitLoading = true
        this.$request(url, { orders: [data], splitDtos: this.splitNum, split: true }, 'post')
          .then((r) => {
            this.$message.success('操作成功')
            this.splitOpen = false
            this.getList()
          })
          .finally(() => {
            this.splitLoading = false
          })
      }
    },
    orderAdd() {
      if (!this.mergeInp) {
        this.$message.error('内容不能为空')
      } else {
        this.orderLoading = true
        let url = this.apiList
        this.$request(
          url,
          {
            page: 1,
            size: 12,
            queryString: {
              order_id: this.mergeInp,
              merge: 1,
            },
          },
          'post',
        )
          .then((r) => {
            this.mergeData = _.uniqWith([...this.mergeChecked, ...r.list], _.isEqual)
            this.mergeData.forEach((v) => {
              if (this.mergeChecked.findIndex((item) => item.id == v.id) >= 0) {
                this.$nextTick(() => {
                  this.$refs.dataTable.toggleRowSelection(v, true)
                })
              }
            })
            if (r.list.length <= 0) {
              this.$message.error('没有找到相应的内容')
            } else {
              this.$message.success('操作成功')
            }
          })
          .finally(() => {
            this.orderLoading = false
          })
      }
    },
    mergeOk() {
      let url = this.apiCreate
      if (this.mergeChecked.length == 1) {
        this.$message.warning('一条是不能合并的哦~~~')
        return false
      }
      if (this.mergeChecked.length == 0) {
        this.$message.warning('没有需要合并的内容')
        return false
      }
      this.mergeLoading = true
      this.$request(url, { orders: [...this.mergeChecked], merge: true }, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.mergeOpen = false
          this.getList()
        })
        .finally(() => {
          this.mergeLoading = false
        })
    },
    statement() {
      let url = this.apiCreate
      let statement_reason = this.statement_reason
      this.statementLoading = true
      this.$request(url, { orders: [{ ...this.statementData, statement_reason }], statement: true }, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.statementOpen = false
          this.getList()
        })
        .finally(() => {
          this.statementLoading = false
        })
    },
    workOrderForm(v) {
      if (v.stauts == '已结单') {
        this.$message.warning('不允许对已结单的订单下工单！！！')
        return false
      }
      this.pageLoading = true
      let url = this.apiSingle || this.api + 'getbyid'
      this.$request(url, {
        vid: v.id,
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          this.workOrderData = this.data
          this.workOrderOpen = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    workOrderSubmit() {
      if (!this.workType || !this.workTime1 || !this.workTime2) {
        this.$message.warning('星号为必填项')
        return false
      }
      let url = this.apiCreate
      this.workOrderLoading = true
      this.$request(
        url,
        {
          orders: [
            {
              ...this.workOrderData,
              mo_type: this.workType,
              mo_no: this.workNum,
              mo_plan_time: this.workTime1,
              mo_target_time: this.workTime2,
            },
          ],
          placeworkorder: true,
        },
        'post',
      )
        .then((r) => {
          this.$message.success('操作成功')
          this.workOrderOpen = false
          this.getList()
        })
        .finally(() => {
          this.workOrderLoading = false
        })
    },
    handleSelectionChange(val) {
      this.mergeChecked = val
    },
  },
}
</script>
<style lang='scss' scoped>
::v-deep .butBlock {
  .el-input-number--small {
    width: 100%;
    input {
      text-align: center;
    }
  }
}

::v-deep .el-input-number--small {
  width: 100%;
  input {
    padding: 0 15px 0 15px;
    text-align: left;
  }
}
</style>